#include "MusicPlayer.h"
#include "ui_MusicPlayer.h"
#include "QDebug"
#include "QFileDialog"
#include "QDir"
#include "QMediaPlayer"
#include "QAudioOutput"
#include "QMediaMetaData"
#include "QUrl"
#include "QImage"
#include "QPixmap"
#include "CustomItemDelegate.h"
#include "QMenu"
#include "QRandomGenerator"
#include "NavigationController.h"

MusicPlayer::MusicPlayer(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MusicPlayer)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/icon/MusicPlayer.ico"));
    setWindowTitle("MyMusicPlayer");
    CustomItemDelegate *delegate = new CustomItemDelegate(this);
    ui->listWidget_musiclist->setItemDelegate(delegate);
    ui->listWidget_collection->setItemDelegate(delegate);
    ui->widget_bottombar->setStyleSheet("border: none;");
    ui->tabWidget->tabBar()->hide();
    ui->tabWidget_switchcontent->tabBar()->hide();
    // 创建音乐播放器
    audioOutput = new QAudioOutput(this);
    mediaPlayer = new QMediaPlayer(this);
    mediaPlayer->setAudioOutput(audioOutput);
    // 获取当前媒体的时长
    connect(mediaPlayer,&QMediaPlayer::durationChanged,this,[=](qint64 duration)
    {
        ui->label_totalTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0')).arg(duration/1000%60));
        ui->horizontalSlider_musicprogress->setRange(0,duration);
    });
    // 获取当前播放的时长
    connect(mediaPlayer,&QMediaPlayer::positionChanged,this,[=](qint64 pos)
    {
        ui->label_currentTime->setText(QString("%1:%2").arg(pos/1000/60,2,10,QChar('0')).arg(pos/1000%60,2,10,QChar('0')));
        ui->horizontalSlider_musicprogress->setValue(pos);
    });
    // 拖动滑块
    connect(ui->horizontalSlider_musicprogress,&QSlider::sliderMoved,mediaPlayer,&QMediaPlayer::setPosition);
    // 调节音量
    audioOutput->setVolume(volume / 100.0);
    ui->horizontalSlider_volume->setValue(volume);
    // 音量更新
    connect(audioOutput, &QAudioOutput::volumeChanged, [=](qreal volume) {
        if (volume == 0) {
            ui->pushButton_volume->setIcon(QIcon(":/icon/noVolume.svg"));
            ui->pushButton_volume->setToolTip("声音");
        } else {
            ui->pushButton_volume->setIcon(QIcon(":/icon/volume.svg"));
            ui->pushButton_volume->setToolTip("静音");
        }
    });
    // 播放状态改变，更新播放按钮和提示
    connect(mediaPlayer, &QMediaPlayer::playbackStateChanged, [=](QMediaPlayer::PlaybackState state) {
        switch (state) {
        case QMediaPlayer::PlayingState:
            ui->pushButton_switch->setToolTip("暂停");
            ui->pushButton_switch->setIcon(QIcon(QPixmap(":/icon/Player, pause.svg")));
            break;
        default:
            ui->pushButton_switch->setToolTip("播放");
            ui->pushButton_switch->setIcon(QIcon(QPixmap(":/icon/Player, play.svg")));
            break;
        }
    });
    // 加载歌曲信息
    connect(mediaPlayer, &QMediaPlayer::mediaStatusChanged, this, [=](QMediaPlayer::MediaStatus status) {
        if (status == QMediaPlayer::LoadedMedia) {
            // 使用 QMediaMetaData::value() 方法获取元数据
            QString title = mediaPlayer->metaData().value(QMediaMetaData::Title).toString();
            QString author = mediaPlayer->metaData().value(QMediaMetaData::Author).toString();
            QImage coverImage = mediaPlayer->metaData().value(QMediaMetaData::ThumbnailImage).value<QImage>();

            ui->label_title_2->setText(title);
            ui->label_author->setText(author);
            if (!coverImage.isNull()) {
                QPixmap coverPixmap = QPixmap::fromImage(coverImage);
                int width = ui->label_coverImage->width();
                int height = ui->label_coverImage->height();
                QPixmap scaledCoverPixmap = coverPixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);
                ui->label_coverImage->setPixmap(scaledCoverPixmap);
            }
        }
    });
    // 设置上下文菜单策略
    ui->listWidget_musiclist->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->listWidget_collection->setContextMenuPolicy(Qt::CustomContextMenu);

}

MusicPlayer::~MusicPlayer()
{
    delete ui;
}


void MusicPlayer::on_pushButton_file_clicked()
{
    // 获取当前文件所在路径
    QString currentDir = QCoreApplication::applicationDirPath();
    QDir tempDir(currentDir);
    tempDir.cdUp();
    tempDir.cdUp();
    tempDir.cdUp();
    currentDir = tempDir.absolutePath();

    // 打开文件对话框
    auto path = QFileDialog::getExistingDirectory(this, "请选择音乐所在的目录", currentDir);

    // 清空之前的列表
    ui->listWidget_musiclist->clear();
    playList.clear();

    // 获取MP3,wav文件并显示
    QDir dir(path);
    auto musicList = dir.entryList(QStringList() << "*.mp3" << "*.wav");

    for (const auto &file : musicList)
    {
        QString filePath = path + "/" + file;

        // 动态创建一个 QMediaPlayer 对象来读取元数据（不播放）
        QMediaPlayer *tempPlayer = new QMediaPlayer(this);
        tempPlayer->setSource(QUrl::fromLocalFile(filePath));
        tempPlayer->setAudioOutput(nullptr); // 不需要输出音频

        // 创建 QListWidgetItem 并设置文件路径作为数据存储
        QListWidgetItem *item = new QListWidgetItem(ui->listWidget_musiclist);
        item->setData(Qt::UserRole + 3, filePath);

        // 使用 lambda 捕捉并更新元数据到列表项
        connect(tempPlayer, &QMediaPlayer::mediaStatusChanged, this, [=](QMediaPlayer::MediaStatus status) {
            if (status == QMediaPlayer::LoadedMedia)
            {
                // 获取元数据
                QString title = tempPlayer->metaData().value(QMediaMetaData::Title).toString();
                QString author = tempPlayer->metaData().value(QMediaMetaData::Author).toString();

                qint64 durationMs = tempPlayer->metaData().value(QMediaMetaData::Duration).toLongLong();
                qint64 durationSec = durationMs / 1000;  // 转换为秒
                int minutes = durationSec / 60;          // 计算分钟
                int seconds = durationSec % 60;          // 计算秒

                // 格式化为 00:00 形式
                QString durationString = QString("%1:%2")
                                             .arg(minutes, 2, 10, QChar('0'))  // 填充分钟部分
                                             .arg(seconds, 2, 10, QChar('0')); // 填充秒部分

                QImage coverImage = tempPlayer->metaData().value(QMediaMetaData::ThumbnailImage).value<QImage>();

                // 如果没有标题，则使用文件名
                if (title.isEmpty()) {
                    title = file;
                }

                // 更新 QListWidgetItem 的数据
                item->setData(Qt::DisplayRole, title);
                item->setData(Qt::UserRole + 1, author);
                item->setData(Qt::UserRole + 2, durationString);

                // 设置封面图片
                if (!coverImage.isNull()) {
                    QPixmap coverPixmap = QPixmap::fromImage(coverImage).scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
                    item->setIcon(QIcon(coverPixmap));
                }

                // 删除 QMediaPlayer 对象
                tempPlayer->deleteLater();

                // 设置歌曲路径数据
                item->setData(Qt::UserRole, filePath);

                // 将项目添加到列表中
                ui->listWidget_musiclist->addItem(item);
            }
        });

        // 保存到播放列表
        playList.append(QUrl::fromLocalFile(filePath));
    }

    // 默认选择第一个音乐
    if (!musicList.isEmpty()) {
        ui->listWidget_musiclist->setCurrentRow(curPlayIndex);
    }
}


void MusicPlayer::on_pushButton_switch_clicked()
{
    if(playList.empty()){
        return;
    }
    switch(mediaPlayer->playbackState()){
        case QMediaPlayer::PlaybackState::StoppedState: // 停止状态
        {
            //播放当前选中的音乐
            // 获取选中的行号
            curPlayIndex = ui->listWidget_musiclist->currentRow();
            // 播放对应下标的音乐
            mediaPlayer->setSource(playList[curPlayIndex]);
            mediaPlayer->play();
            break;
        }
        case QMediaPlayer::PlaybackState::PlayingState: // 播放状态
        {
            // 暂停音乐
            mediaPlayer->pause();
            break;
        }
        case QMediaPlayer::PlaybackState::PausedState: // 暂停状态
        {
            // 播放音乐
            mediaPlayer->play();
            break;
        }
    }

}


void MusicPlayer::on_pushButton_lastsong_clicked()
{
    // 播放上一首音乐
    switch (currentPlayMode) {
    case playMode::Sequential:
        curPlayIndex = (curPlayIndex - 1) % playList.size();
        break;

    case playMode::Loop:
        break;

    case playMode::Shuffle:
        int newIndex;
        do {
            newIndex = QRandomGenerator::global()->bounded(playList.size());
        } while (newIndex == curPlayIndex);
        curPlayIndex = newIndex;
        break;
    }
    ui->listWidget_musiclist->setCurrentRow(curPlayIndex);
    mediaPlayer->setSource(playList[curPlayIndex]);
    mediaPlayer->play();
}


void MusicPlayer::on_pushButton_nextsong_clicked()
{
    // 播放下一首音乐
    switch (currentPlayMode) {
    case playMode::Sequential:
        curPlayIndex = (curPlayIndex + 1) % playList.size();
        break;

    case playMode::Loop:
        break;

    case playMode::Shuffle:
        int newIndex;
        do {
            newIndex = QRandomGenerator::global()->bounded(playList.size());
        } while (newIndex == curPlayIndex);
        curPlayIndex = newIndex;
        break;
    }

    ui->listWidget_musiclist->setCurrentRow(curPlayIndex);
    mediaPlayer->setSource(playList[curPlayIndex]);
    mediaPlayer->play();
}

void MusicPlayer::on_listWidget_musiclist_doubleClicked(const QModelIndex &index)
{
    // 双击播放音乐
    int newIndex = index.row();
    if (newIndex < 0 || newIndex >= playList.size()) {
        return; // 避免数组越界
    }

    curPlayIndex = newIndex;
    mediaPlayer->setSource(playList[curPlayIndex]);
    mediaPlayer->play();
}

void MusicPlayer::on_listWidget_collection_doubleClicked(const QModelIndex &index)
{
    // 双击播放音乐
    int newIndex = index.row();
    if (newIndex < 0 || newIndex >= playList.size()) {
        return; // 避免数组越界
    }

    curPlayIndex = newIndex;
    mediaPlayer->setSource(playList[curPlayIndex]);
    mediaPlayer->play();
}

void MusicPlayer::on_horizontalSlider_volume_valueChanged(int value)
{
    volume = value;
    qreal scaledVolume = volume / 100.0;  // 将整数音量转换为0.0到1.0之间的值
    audioOutput->setVolume(scaledVolume);
}

void MusicPlayer::on_pushButton_volume_clicked()
{
    if (0 == audioOutput->volume()) {
        qreal scaledVolume = volume / 100.0;
        audioOutput->setVolume(scaledVolume);
        ui->horizontalSlider_volume->setEnabled(true);
        ui->horizontalSlider_volume->setValue(volume);
        ui->pushButton_volume->setIcon(QIcon(":/icon/volume.svg"));
        ui->pushButton_volume->setToolTip("静音");
    }
    else {
        audioOutput->setVolume(0);
        ui->horizontalSlider_volume->setEnabled(false);
        ui->pushButton_volume->setIcon(QIcon(":/icon/noVolume.svg"));
        ui->pushButton_volume->setToolTip("声音");
    }
}

void MusicPlayer::setPlayMode(playMode newMode) {
    // 设置播放模式
    currentPlayMode = newMode;
}


void MusicPlayer::on_pushButton_mode_clicked()
{
    if (currentPlayMode == playMode::Sequential) {
        setPlayMode(playMode::Loop);
        ui->pushButton_mode->setIcon(QIcon(":/icon/repeat.svg"));
    } else if (currentPlayMode == playMode::Loop) {
        setPlayMode(playMode::Shuffle);
        ui->pushButton_mode->setIcon(QIcon(":/icon/random.svg"));
    } else {
        setPlayMode(playMode::Sequential);
        ui->pushButton_mode->setIcon(QIcon(":/icon/order-play-fill.svg"));
    }
}


void MusicPlayer::on_listWidget_musiclist_customContextMenuRequested(const QPoint &pos)
{
    // 获取点击位置的项
    QListWidgetItem *item = ui->listWidget_musiclist->itemAt(pos);
    if (!item){
        return; // 如果点击位置没有项，直接返回
    }

    // 创建上下文菜单
    QMenu contextMenu(this);

    // 添加“播放歌曲”选项
    QAction *playAction = new QAction("播放歌曲", this);
    connect(playAction, &QAction::triggered, this, [this, item]() {
        playSong(item);  // 实现播放歌曲的逻辑
    });
    contextMenu.addAction(playAction);

    // 添加“添加到我的收藏”选项
    QAction *addToFavoritesAction = new QAction("添加到我的收藏", this);
    connect(addToFavoritesAction, &QAction::triggered, this, [this, item]() {
        addToFavorites(item);  // 实现添加到收藏的逻辑
    });
    contextMenu.addAction(addToFavoritesAction);

    // 在点击位置显示上下文菜单
    contextMenu.exec(ui->listWidget_musiclist->viewport()->mapToGlobal(pos));
}

void MusicPlayer::on_listWidget_collection_customContextMenuRequested(const QPoint &pos)
{
    // 获取点击位置的项
    QListWidgetItem *item = ui->listWidget_collection->itemAt(pos);
    if (!item){
        return; // 如果点击位置没有项，直接返回
    }

    // 创建上下文菜单
    QMenu contextMenu(this);

    // 添加“播放歌曲”选项
    QAction *playAction = new QAction("播放歌曲", this);
    connect(playAction, &QAction::triggered, this, [this, item]() {
        playSong(item);  // 实现播放歌曲的逻辑
    });
    contextMenu.addAction(playAction);

    // 添加“取消收藏”选项
    QAction *deleteFavoritesAction = new QAction("取消收藏", this);
    connect(deleteFavoritesAction, &QAction::triggered, this, [this, item]() {
        deleteFavorites(item);  // 实现取消收藏的逻辑
    });
    contextMenu.addAction(deleteFavoritesAction);

    // 在点击位置显示上下文菜单
    contextMenu.exec(ui->listWidget_musiclist->viewport()->mapToGlobal(pos));
}

void MusicPlayer::playSong(QListWidgetItem *item)
{
    // 从 item 中提取歌曲路径
    QString songPath = item->data(Qt::UserRole).toString();

    if (songPath.isEmpty()) {
        return;
    }

    int newIndex = ui->listWidget_musiclist->indexFromItem(item).row();
    if (newIndex < 0 || newIndex >= playList.size()) {
        return; // 避免数组越界
    }

    curPlayIndex = newIndex;
    mediaPlayer->setSource(QUrl::fromLocalFile(songPath));
    mediaPlayer->play();
}



void MusicPlayer::addToFavorites(QListWidgetItem *item)
{
    // 从 item 中提取歌曲路径
    QString songPath = item->data(Qt::UserRole).toString();

    // 检查收藏列表中是否已存在该歌曲
    for (int i = 0; i < ui->listWidget_collection->count(); ++i) {
        QListWidgetItem *existingItem = ui->listWidget_collection->item(i);
        QString existingSongPath = existingItem->data(Qt::UserRole).toString();

        if (existingSongPath == songPath) {
            // 如果歌曲已经存在于收藏列表中，直接返回
            return;
        }
    }

    // 创建一个新的 QListWidgetItem 并复制原项目的数据
    QListWidgetItem *newItem = new QListWidgetItem(*item);

    // 将项目添加到列表中
    ui->listWidget_collection->addItem(newItem);

    // 保存到收藏列表
    collectionList.append(QUrl::fromLocalFile(songPath));
}

void MusicPlayer::deleteFavorites(QListWidgetItem *item) {
    if (!item) return;  // 检查指针是否为空

    // 获取当前选中项的文件路径
    QString songPath = item->data(Qt::UserRole + 3).toString();

    // 遍历收藏列表，找到匹配的项
    for (int i = 0; i < ui->listWidget_collection->count(); ++i) {
        QListWidgetItem *existingItem = ui->listWidget_collection->item(i);
        QString existingSongPath = existingItem->data(Qt::UserRole + 3).toString();

        if (existingSongPath == songPath) {
            // 从 QListWidget 中移除项目
            delete ui->listWidget_collection->takeItem(i);

            // 从 collectionList 中删除对应的 URL
            collectionList.removeOne(QUrl::fromLocalFile(existingSongPath));

            // 退出循环
            break;
        }
    }
}



void MusicPlayer::on_pushButton_musiclist_clicked()
{
    ui->tabWidget_switchcontent->setCurrentIndex(0); // 音乐列表
}


void MusicPlayer::on_pushButton_collection_clicked()
{
    ui->tabWidget_switchcontent->setCurrentIndex(1); // 我的收藏
}


void MusicPlayer::on_pushButton_home_clicked()
{
    mediaPlayer->pause();
    MyNavigationController::instance().backToMainPage();
}

